﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MySql.Data.MySqlClient;

namespace PACKETPARSERMAX20.CONSOLE
{
    public static class DBParserDump
    {

        public static string GetConnectionString(string pDataBase)
        {
            //"DRIVER={MySQL ODBC 5.1 Driver};SERVER=" + Server + ";DATABASE=" + pDataBase + ";UID=" + UserID + ";PASSWORD=" + Password + ";OPTION=3";
            MySql.Data.MySqlClient.MySqlConnectionStringBuilder tMySqlConnectionStringBuilder = new MySql.Data.MySqlClient.MySqlConnectionStringBuilder();
            tMySqlConnectionStringBuilder.AllowBatch = true;
            tMySqlConnectionStringBuilder.Database = pDataBase;
            tMySqlConnectionStringBuilder.UserID = "root";
            tMySqlConnectionStringBuilder.Password = "root";
            tMySqlConnectionStringBuilder.Server = "mikedb01";
            tMySqlConnectionStringBuilder.Port = 3306;
            tMySqlConnectionStringBuilder.PersistSecurityInfo = false;
            return tMySqlConnectionStringBuilder.ConnectionString;
        }

        public static void GenerateCode()
        {
            GenerateCodeForTable("creature_template");
            GenerateCodeForTable("creature_equip_template");
            GenerateCodeForTable("creature_template_addon");
            GenerateCodeForTable("quest_template");
            GenerateCodeForTable("item_template");
            GenerateCodeForTable("gameobject_template");
            GenerateCodeForTable("npc_text");
            GenerateCodeForTable("npc_trainer");
            GenerateCodeForTable("npc_vendor");
            GenerateCodeForTable("creature");
            GenerateCodeForTable("creature_addon");
            GenerateCodeForTable("creature_movement");
            GenerateCodeForTable("creature_questrelation");
            GenerateCodeForTable("creature_involvedrelation");
            GenerateCodeForTable("gameobject");
            GenerateCodeForTable("gossip_menu");
            GenerateCodeForTable("gossip_menu_option");
        }

        public static void GenerateCodeForTable(string pTableName)
        {
            if (!System.IO.Directory.Exists(".\\MangosTables\\")) System.IO.Directory.CreateDirectory(".\\MangosTables\\");
            using (System.IO.StreamWriter sw = new System.IO.StreamWriter(".\\MangosTables\\" + pTableName + ".cs"))
            {
                using (MySqlConnection con = new MySqlConnection(GetConnectionString("mangos")))
                {
                    con.Open();
                    using (MySqlCommand command = con.CreateCommand())
                    {

                        command.CommandType = System.Data.CommandType.Text;
                        command.CommandText = string.Format("select * from {0} limit 1", pTableName);

                        try
                        {
                            StringBuilder sb_object = new StringBuilder();
                            StringBuilder sb_Insert_part1 = new StringBuilder();
                            StringBuilder sb_Insert_part2 = new StringBuilder();
                            StringBuilder sb_Insert_part3 = new StringBuilder();
                            StringBuilder sb_Update_part1 = new StringBuilder();
                            StringBuilder sb_Update_part2 = new StringBuilder();
                            sb_Insert_part1.Append(string.Format("INSERT IGNORE INTO `{0}` (", pTableName.ToLower()));
                            sb_Insert_part2.Append(" VALUES (");

                            sb_Update_part1.Append(string.Format("UPDATE `{0}` SET", pTableName.ToLower()));
                            sb_Update_part2.Append("\", ");
                            sb_Insert_part3.Append("\", ");

                            using (MySqlDataReader dr = command.ExecuteReader())
                            {

                                for (int i = 0; i < dr.FieldCount; i++)
                                {
                                    if (i == dr.FieldCount - 1)
                                    {
                                        sb_Insert_part1.Append(string.Format("`{0}`)", dr.GetName(i).ToLower()));
                                        sb_Insert_part2.Append("'{" + i.ToString() + "}');");
                                        sb_Insert_part3.Append(dr.GetName(i).ToLower() + ");");
                                        sb_Update_part1.Append("`" + dr.GetName(i).ToLower() + "`='{" + i.ToString() + "}' ");
                                    }
                                    else
                                    {
                                        sb_Insert_part1.Append(string.Format("`{0}`, ", dr.GetName(i).ToLower()));
                                        sb_Insert_part2.Append("'{" + i.ToString() + "}', ");
                                        sb_Update_part1.Append("`" + dr.GetName(i).ToLower() + "`='{" + i.ToString() + "}', ");

                                        if (dr.GetFieldType(i) == typeof(System.String))
                                        {
                                            sb_Insert_part3.Append(dr.GetName(i).ToLower() + ".MySQLDBString(), ");
                                        }
                                        else
                                        {
                                            sb_Insert_part3.Append(dr.GetName(i).ToLower() + ", ");
                                        }

                                    }

                                    sb_object.AppendLine(string.Format("\t\tpublic {0} {1};", dr.GetFieldType(i), dr.GetName(i).ToLower()));

                                    if (dr.GetFieldType(i) == typeof(System.String))
                                    {
                                        sb_Update_part2.Append(dr.GetName(i).ToLower() + ".MySQLDBString(), ");
                                    }
                                    else
                                    {
                                        sb_Update_part2.Append(dr.GetName(i).ToLower() + ", ");
                                    }
                                }

                                sb_Update_part1.Append("WHERE `" + dr.GetName(0).ToLower() + "`='{" + dr.FieldCount.ToString() + "}';");
                                sb_Update_part2.Append(dr.GetName(0).ToLower() + ");");
                            }

                            sw.WriteLine("using System;");
                            sw.WriteLine("using System.Collections.Generic;");
                            sw.WriteLine("using System.Linq;");
                            sw.WriteLine("using System.Text;");
                            sw.WriteLine();
                            sw.WriteLine("namespace PACKETPARSERMAX20.CORE");
                            sw.WriteLine("{");
                            sw.WriteLine("\tpublic class " + pTableName.ToLower() + " : MangosBase");
                            sw.WriteLine("\t{");
                            sw.WriteLine(sb_object);
                            sw.WriteLine();
                            sw.WriteLine();
                            sw.WriteLine("\t\tpublic override string GetInsertCommand()\n\t\t{\n\t\t\treturn string.Format(\"" + sb_Insert_part1.ToString() + sb_Insert_part2.ToString() + sb_Insert_part3.ToString() + "\n\t\t}");
                            sw.WriteLine();
                            sw.WriteLine();
                            sw.WriteLine("\t\tpublic override string GetUpdateCommand()\n\t\t{\n\t\t\treturn string.Format(\"" + sb_Update_part1.ToString() + sb_Update_part2.ToString() + "\n\t\t}");
                            sw.WriteLine();
                            sw.WriteLine();
                            sw.WriteLine("\t}");
                            sw.WriteLine("}");
                        }
                        catch (Exception exc)
                        {
                            Console.WriteLine("Error: {0}, {1}", exc.Message, command.CommandText);
                        }
                    }

                }
                sw.Close();
            }
        }

        public static void Process()
        {

            string[] files = System.IO.Directory.GetFiles(@"\\mikedb01\E\_SQLS\parserdump_32X\sql_10482_to_10505\gameobject_template\");

            foreach (string file in files)
            {
                System.IO.FileInfo info = new System.IO.FileInfo(file);
                string name = System.IO.Path.GetFileNameWithoutExtension(file);
                bool is_item_template_new = name.Equals("item_template_up");
                using (System.IO.StreamReader sr = new System.IO.StreamReader(file))
                {
                    using (MySqlConnection con = new MySqlConnection(GetConnectionString("parserdump_32x")))
                    {
                        con.Open();


                        using (MySqlTransaction dbTrans = con.BeginTransaction())
                        {
                            while (!sr.EndOfStream)
                            {
                                using (MySqlCommand command = con.CreateCommand())
                                {
                                    string sql = sr.ReadLine();
                                    command.CommandType = System.Data.CommandType.Text;

                                    if (is_item_template_new)
                                    {

                                        sql = sql.Replace("`AllowableRace`='2147483647'", "`AllowableRace`='-1'");
                                        sql = sql.Replace("`RandomProperty`='-1'", "`RandomProperty`='0'");

                                        for (int i = 1; i < 6; i++)
                                        {
                                            sql = sql.Replace("`spellid_" + i.ToString() + "` = '-1'", "`spellid_" + i.ToString() + "` = '0'");
                                        }

                                    }
                                    command.CommandText = sql;


                                    try
                                    {

                                        if (command.ExecuteNonQuery() <= 0)
                                        {
                                            throw new Exception("record not inserted?");
                                        }
                                    }
                                    catch (Exception exc)
                                    {
                                        Console.WriteLine("Error: {0}, {1}", exc.Message, sql);
                                    }
                                }
                            }

                            dbTrans.Commit();


                        }

                        con.Close();
                    }

                    sr.Close();
                }
            }
        }

        public static void Process(string pSource, string pDataBase, bool pInsert, bool pUpdate)
        {
            string[] files = System.IO.Directory.GetFiles(pSource);

            int i = 0;

            foreach (string file in files)
            {
                bool execute = false;

                if (file.IndexOf("_update.sql") != -1)
                    execute = pUpdate;
                else if (file.IndexOf("_insert.sql") != -1)
                    execute = pInsert;

                if (execute)
                {

                    using (System.IO.StreamReader sr = new System.IO.StreamReader(file))
                    {
                        using (MySqlConnection con = new MySqlConnection(GetConnectionString(pDataBase)))
                        {
                            con.Open();

                            using (MySqlTransaction dbTrans = con.BeginTransaction())
                            {
                                while (!sr.EndOfStream)
                                {
                                    using (MySqlCommand command = con.CreateCommand())
                                    {
                                        string sql = sr.ReadLine();
                                        command.CommandType = System.Data.CommandType.Text;
                                        command.CommandText = sql;

                                        try
                                        {
                                            if (command.ExecuteNonQuery() <= 0)
                                            {
                                                throw new Exception("record not inserted?");
                                            }
                                        }
                                        catch (Exception exc)
                                        {
                                            Console.WriteLine("Error: {0}, {1}", exc.Message, sql);
                                        }
                                    }
                                }

                                dbTrans.Commit();
                            }

                            con.Close();
                        }

                        sr.Close();
                    }
                }

                i++;
                Common.WritePercent(i, files.Length);

            }
        }
    }
}
